package com.dd.cloud.user.service.supervision.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dd.cloud.common.exception.ZekeException;
import com.dd.cloud.common.utils.ExtUtils;
import com.dd.cloud.user.entity.supervision.SupervisionData;
import com.dd.cloud.user.mapper.spervision.SupervisionDataMapper;
import com.dd.cloud.user.req.supervision.SupervisionExcel;
import com.dd.cloud.user.service.supervision.ISupervisionDataService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static com.dd.cloud.common.utils.ExtUtils.getWorkBook;

/**
 * <p>
 * 医疗监管数据 服务实现类
 * </p>
 *
 * @author czg
 * @since 2023-07-21
 */
@Service
public class SupervisionDataServiceImpl extends ServiceImpl<SupervisionDataMapper, SupervisionData> implements ISupervisionDataService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importData(MultipartFile file) {
        if (file == null) {
            throw new ZekeException(400, "请上传文件");
        }
        if (!file.getOriginalFilename().contains(".xlsx") && !file.getOriginalFilename().contains(".xls")) {
            throw new ZekeException(400, "只支持xlsx和xls文件格式");
        }
        //根据file得到Workbook,主要是要根据这个对象获取,传过来的excel有几个sheet页
        List<SupervisionExcel> list = new ArrayList<>();
        List<SupervisionData> supervisionDataList = new ArrayList<>();
        Workbook hssfWorkbook = null;
        try {
            hssfWorkbook = getWorkBook(file.getInputStream(), null);
        } catch (IOException e) {
            e.printStackTrace();
            throw new ZekeException(400, "解析Excel失败");
        }
//            获取sheet数量
        int sheetNum = hssfWorkbook.getNumberOfSheets();

        for (int sheetIndex = 0; sheetIndex < sheetNum; sheetIndex++) {
            try {
                list = ExtUtils.importExcel(file.getInputStream(), sheetIndex, 0, 1, SupervisionExcel.class);
            } catch (IOException e) {
                throw new ZekeException(400, "解析Excel失败");
            }
            if (list == null || list.isEmpty()) {
                throw new ZekeException(400, "文档数据为空");
            }
            for (SupervisionExcel supervisionExcel : list) {
                SupervisionData supervisionData = new SupervisionData();
                BeanUtils.copyProperties(supervisionExcel, supervisionData);
                supervisionData.setType(sheetIndex + 1);
                supervisionDataList.add(supervisionData);
            }
        }
        if (CollectionUtils.isNotEmpty(supervisionDataList)) {
            this.saveBatch(supervisionDataList);
        }
    }
}
